package main

import (
	"flag"
	"log"
	"net"

	"gitee.com/terender/tcptunnel/stream"

	"gitee.com/terender/sfw/quit"
	"gitee.com/terender/sfw/rlog"
)

func main() {

	port := flag.String(`p`, `9527`, `Listening port`)
	remote := flag.String(`r`, ``, `Remote address`)
	flag.Parse()
	if *port == `` || *remote == `` {
		flag.PrintDefaults()
		return
	}

	addr, err := net.ResolveTCPAddr(`tcp`, *remote)
	if err != nil {
		log.Print(err)
		flag.PrintDefaults()
		return
	}

	rlog.Init(`tcptunnel`, false)
	defer rlog.Quit()

	quit.WatchStdKillSignal()

	go func() {
		listener, err := net.Listen("tcp", `:`+*port)
		if err != nil {
			rlog.Errorf("listening err:%s", err.Error())
			return
		}
		log.Printf(`listening on port %s`, *port)

		for {
			conn, err := listener.Accept()
			if err != nil {
				rlog.Errorf("accept err(before): %s ", err.Error())
				if ne, ok := err.(net.Error); ok && ne.Temporary() {
					rlog.Infof("accept net error: %+v", ne)
					continue
				}
				rlog.Errorf("accept error(after): %+v", err.Error())
				return
			}
			go func(conn net.Conn) {
				remote, err := net.DialTCP(`tcp`, nil, addr)
				if err != nil {
					rlog.Errorf(`Try to connect %s encounterd an error: %v`, *remote, err)
					return
				}
				//log.Printf(`建立了到 %s --- %s 的连接`, conn.RemoteAddr().String(), remote.RemoteAddr().String())
				go stream.UpStream(conn, remote)
				go stream.DownStream(conn, remote)
			}(conn)
		}
	}()

	quit.Wait()
}
